package com.huashi.dealer.core.util;

import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import jakarta.annotation.Resource;
import java.util.Set;

/**
 * Redis缓存工具类
 * 用于清除sa-token相关的缓存数据
 *
 * @author 系统
 * @since 2025-08-29
 */
//@Component
public class RedisCacheUtil {

    @Resource
    private RedisTemplate<String, Object> redisTemplate;

    /**
     * 清除sa-token相关的所有缓存
     */
    public void clearSaTokenCache() {
        try {
            // 清除以satoken:开头的key
            Set<String> keys = redisTemplate.keys("satoken:*");
            if (keys != null && !keys.isEmpty()) {
                redisTemplate.delete(keys);
                System.out.println("已清除 " + keys.size() + " 个sa-token缓存key");
            }

            // 清除以store_开头的session key
            keys = redisTemplate.keys("store_*");
            if (keys != null && !keys.isEmpty()) {
                redisTemplate.delete(keys);
                System.out.println("已清除 " + keys.size() + " 个store session缓存key");
            }

        } catch (Exception e) {
            System.err.println("清除Redis缓存时发生错误: " + e.getMessage());
            e.printStackTrace();
        }
    }

    /**
     * 清除指定模式的缓存
     * @param pattern 匹配模式，如 "satoken:*" 或 "*"
     */
    public void clearCacheByPattern(String pattern) {
        try {
            Set<String> keys = redisTemplate.keys(pattern);
            if (keys != null && !keys.isEmpty()) {
                redisTemplate.delete(keys);
                System.out.println("已清除 " + keys.size() + " 个匹配 '" + pattern + "' 的缓存key");
            } else {
                System.out.println("没有找到匹配 '" + pattern + "' 的缓存key");
            }
        } catch (Exception e) {
            System.err.println("清除缓存时发生错误: " + e.getMessage());
            e.printStackTrace();
        }
    }
}
